package com.imooc.shell.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.Arrays;

@RestController
@Slf4j
@RequestMapping("/weixin")
public class WeixinController {
    private static final String token = "accesstoken";

    @GetMapping("/auth")
    public void auth(@RequestParam("code") String code) {
        log.info("进入 auth方法 。。。");
        log.info("获取到 code== {}", code);
    }

    @GetMapping("/toauth")
    public void auth() {
        String encode = URLEncoder.encode("http://sdf2e9.natappfree.cc/sell/weixin/auth");
        String url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx15cef5c37b9d10fe&redirect_uri="+encode+"&response_type=code&scope=snsapi_userinfo&state=abcdeft#wechat_redirect ";
        log.info("获取到 url== {}", url);
    }

    @GetMapping("/service")
    public String  service(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr
    ) {
        //1.定义数组存放tooken，timestamp,nonce
        String[] arr = {token, timestamp, nonce};
        //2.对数组进行排序
        Arrays.sort(arr);

        //3.生成字符串
        StringBuffer sb = new StringBuffer();

        for (String s : arr) {

            sb.append(s);

        }
        //4.sha1加密,网上均有现成代码
        String temp = getSha1(sb.toString());
        //5.将加密后的字符串，与微信传来的加密签名比较，返回结果
        return  echostr;
//        return temp.equals(signature);
    }

    // sha1 加密
    protected static String getSha1(String str){

        if(str==null||str.length()==0){

            return null;

        }

        char hexDigits[] = {'0','1','2','3','4','5','6','7','8','9',

                'a','b','c','d','e','f'};

        try {

            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");

            mdTemp.update(str.getBytes("UTF-8"));



            byte[] md = mdTemp.digest();

            int j = md.length;

            char buf[] = new char[j*2];

            int k = 0;

            for (int i = 0; i < j; i++) {

                byte byte0 = md[i];

                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];

                buf[k++] = hexDigits[byte0 & 0xf];

            }

            return new String(buf);

        } catch (Exception e) {

            // TODO: handle exception

            return null;

        }

    }
}
